package examples;

import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import au.com.bytecode.opencsv.CSVReader;

public class XPathExample {

	private static final String CSV_FILE = "books.csv";

	public static void processCsv() throws IOException {

		CSVReader reader = new CSVReader(new FileReader(CSV_FILE));
		String[] nextLine;
		while ((nextLine = reader.readNext()) != null) {
			System.out.println("year: " + nextLine[0] + "\ntitle: "
		  + nextLine[1] + "\nauthor: " + nextLine[2] + "\npublisher: " 
		  + nextLine[3] + "\nisbn: " + nextLine[4] + "\nprice: " + nextLine[5]);
			System.out.println("============================");
		}

	}

	public static void  processXpath() throws ParserConfigurationException,
			SAXException, IOException, XPathExpressionException {

		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		domFactory.setNamespaceAware(true); // never forget this!
		DocumentBuilder builder = domFactory.newDocumentBuilder();
		Document doc = builder.parse("books.xml");
		//Document doc = builder.parse("content_2010.xml");

		XPathFactory factory = XPathFactory.newInstance();
		XPath xpath = factory.newXPath();
		XPathExpression expr = xpath.compile("//book[author='Neal Stephenson']/price/text()");
		

		Object result = expr.evaluate(doc, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		for (int i = 0; i < nodes.getLength(); i++) {
//			System.out.println(nodes.item(i).getNodeValue());
			nodes.item(i).setNodeValue(null);
		}
		System.out.println("Done");
	}
	public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		processCsv();
		processXpath();
	}
}